package org.kojo.tdrm.service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.jdo.PersistenceManager;

import org.kojo.tdrm.entity.Task;
import org.kojo.tdrm.persistence.PMF;

public class RepeatTaskAppService {
	public void process() {
		TaskAppService service = new TaskAppService();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<Task> tasks = service.listRepeatTask(pm);
		Date current = new Date();
		for (Task task : tasks) {
			Date dueDate = task.getDueDate();
			Date nextDueDate = this.getNextDueDate(current, dueDate, task.getRepeatType(), task.getRepeatEvery());
			if(!dueDate.equals(nextDueDate)){
				task.setDueDate(nextDueDate);
				task.setState(Task.ONGOING);
			}
		}
		pm.currentTransaction().begin();
		service.saveTask(pm, tasks);
		pm.currentTransaction().commit();
		pm.close();
	}

	public Date getNextDueDate(Date currentDate, Date dueDate, int repeatType,
			int repeatEvery) {
		Date nextDueDate = null;
		if (currentDate.after(dueDate)) {
			Calendar cal = Calendar.getInstance(Locale.US);
			cal.setTime(dueDate);
			if (repeatType == Task.DAILY) {
				cal.add(Calendar.DAY_OF_MONTH, repeatEvery);
				nextDueDate = cal.getTime();
			}
			if (repeatType == Task.MONTHLY) {
				cal.add(Calendar.MONTH, repeatEvery);
				nextDueDate = cal.getTime();
			}
		} else {
			nextDueDate = dueDate;
		}

		return nextDueDate;
	}
}
